package com.example.authsystem.controller;

import com.example.authsystem.dto.JwtResponse;
import com.example.authsystem.dto.LoginRequest;
import com.example.authsystem.dto.RegisterRequest;
import com.example.authsystem.dto.UserProfileDto;
import com.example.authsystem.dto.UserListResponse;
import com.example.authsystem.entity.User;
import com.example.authsystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户认证和信息管理接口")
public class UserController {

    @Autowired
    private UserService userService;

    // 原始认证相关接口
    @Operation(summary = "用户注册", description = "创建新用户账户")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "注册成功",
                    content = @Content(schema = @Schema(implementation = User.class))
            ),
            @ApiResponse(responseCode = "400", description = "用户名或邮箱已存在")
    })
    @PostMapping("/register")
    public ResponseEntity<User> registerUser(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "注册请求信息",
                    required = true,
                    content = @Content(schema = @Schema(implementation = RegisterRequest.class))
            )
            @RequestBody RegisterRequest registerRequest) {

        User user = userService.registerUser(registerRequest);
        return ResponseEntity.ok(user);
    }

    @Operation(summary = "用户登录", description = "验证用户凭据并返回JWT令牌，支持用户名、邮箱或手机号登录")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "登录成功",
                    content = @Content(schema = @Schema(implementation = JwtResponse.class))
            ),
            @ApiResponse(responseCode = "400", description = "凭据错误或账户异常"),
            @ApiResponse(responseCode = "401", description = "手机号格式不正确")
    })
    @PostMapping("/login")
    public ResponseEntity<JwtResponse> loginUser(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "登录凭据",
                    required = true,
                    content = @Content(schema = @Schema(implementation = LoginRequest.class))
            )
            @RequestBody LoginRequest loginRequest,
            @Parameter(description = "设备标识符")
            @RequestHeader(value = "Device-ID", defaultValue = "unknown") String deviceId,
            @Parameter(description = "登录位置")
            @RequestHeader(value = "Location", defaultValue = "unknown") String location) {

        JwtResponse response = userService.loginUser(loginRequest, deviceId, location);
        return ResponseEntity.ok(response);
    }

    @Operation(summary = "刷新令牌", description = "使用刷新令牌获取新的访问令牌")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "刷新成功"),
            @ApiResponse(responseCode = "401", description = "刷新令牌无效或已过期"),
            @ApiResponse(responseCode = "403", description = "用户账户异常")
    })
    @PostMapping("/refresh-token")
    public ResponseEntity<String> refreshToken(
            @Parameter(description = "刷新令牌")
            @RequestHeader("Authorization") String authHeader) {

        // 提取Bearer token
        String refreshToken = authHeader.startsWith("Bearer ") ?
                authHeader.substring(7) : authHeader;

        String newToken = userService.refreshToken(refreshToken);
        return ResponseEntity.ok(newToken);
    }

    // 用户管理相关接口
    @Operation(summary = "获取用户列表", description = "分页获取用户列表")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "获取成功",
                    content = @Content(schema = @Schema(implementation = UserListResponse.class))
            ),
            @ApiResponse(responseCode = "400", description = "参数错误")
    })
    @GetMapping
    public ResponseEntity<UserListResponse> getUserList(
            @Parameter(description = "页码，从1开始")
            @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小")
            @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "用户名关键词")
            @RequestParam(required = false) String keyword) {

        UserListResponse response = userService.getUserList(page, size, keyword);
        return ResponseEntity.ok(response);
    }

    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "获取成功",
                    content = @Content(schema = @Schema(implementation = UserProfileDto.class))
            ),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/{userId}")
    public ResponseEntity<UserProfileDto> getUserProfile(
            @Parameter(description = "用户ID")
            @PathVariable Long userId) {

        UserProfileDto profile = userService.getUserProfile(userId);
        return ResponseEntity.ok(profile);
    }

    @Operation(summary = "更新用户信息", description = "更新指定用户的基本信息")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "更新成功",
                    content = @Content(schema = @Schema(implementation = UserProfileDto.class))
            ),
            @ApiResponse(responseCode = "404", description = "用户不存在"),
            @ApiResponse(responseCode = "400", description = "参数错误")
    })
    @PutMapping("/{userId}")
    public ResponseEntity<UserProfileDto> updateUser(
            @Parameter(description = "用户ID")
            @PathVariable Long userId,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "用户信息",
                    required = true,
                    content = @Content(schema = @Schema(implementation = UserProfileDto.class))
            )
            @RequestBody UserProfileDto userDto) {

        UserProfileDto updated = userService.updateUserProfile(userId, userDto);
        return ResponseEntity.ok(updated);
    }

    @Operation(summary = "删除用户", description = "软删除指定用户")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @DeleteMapping("/{userId}")
    public ResponseEntity<Void> deleteUser(
            @Parameter(description = "用户ID")
            @PathVariable Long userId) {

        userService.deleteUser(userId);
        return ResponseEntity.ok().build();
    }
}
